package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
)

func main() {
	//f2("test",1,2,3,4,5)
	ages := [3]int{1, 2, 3}
	var ages1 [10]int
	fmt.Println(ages)
	//var a int = 10
	fmt.Printf("变量的地址: %x\n", &ages[1])
	fmt.Printf("变量的ages1[1]地址: %d--%x\n", ages1[1], &ages1[1])
	//str := "a"
	//str, _ := os.Getwd()
	WalkDir("/Users/huanglu/Desktop/test/video")
}

func f1(x, y, z int, m, n string, i, j bool) int {
	return x + y + z
}

func f2(x string, y ...int) {
	fmt.Println(x)
	fmt.Println(y)
	fmt.Printf("%T", y)
}

func WalkDir(dir string) {
	filepath.Walk(dir, func(fileName string, fi os.FileInfo, err error) error {
		if !fi.IsDir() {
			fmt.Println(fileName)
			ext := path.Ext(fileName)
			name := strings.TrimSuffix(fileName, ext)

			if ext == ".dav" {
				c := `ffmpeg -i ` + fileName + ` -vcodec copy -acodec copy ` + name + ".mp4"
				fmt.Println(c)
				ExecCommand(c)
				err := os.Remove(fileName) //删除文件

				if err != nil {

					//如果删除失败则输出 file remove Error!

					fmt.Println("file remove Error!")

					//输出错误详细信息

					fmt.Printf("%s", err)

				} else {

					//如果删除成功则输出 file remove OK!

					fmt.Print("file remove OK!")

				}
			}

		}
		return nil
	})
}

// ExecCommand 运行命令并实时查看运行结果
func ExecCommand(command string) error {
	cmd := exec.Command("bash", "-c", command)

	stdout, _ := cmd.StdoutPipe()
	stderr, _ := cmd.StderrPipe()

	if err := cmd.Start(); err != nil {
		log.Println("Error:The command is err: ", err.Error())
		return err
	}
	ch := make(chan string, 100)
	stdoutScan := bufio.NewScanner(stdout)
	stderrScan := bufio.NewScanner(stderr)
	go func() {
		for stdoutScan.Scan() {
			line := stdoutScan.Text()
			ch <- line
		}
	}()
	go func() {
		for stderrScan.Scan() {
			line := stderrScan.Text()
			ch <- line
		}
	}()
	var err error
	go func() {
		err = cmd.Wait()
		if err != nil && !strings.Contains(err.Error(), "exit status") {
			log.Println("wait:", err.Error())
		}
		close(ch)
	}()
	for line := range ch {
		log.Println(line)
	}
	return err
}

// ExecCommandWithResult 运行命令并获取结果
func ExecCommandWithResult(command string) string {
	out, err := exec.Command("bash", "-c", command).CombinedOutput()
	if err != nil && !strings.Contains(err.Error(), "exit status") {
		log.Println("err: " + err.Error())
		return ""
	}
	return string(out)
}
